package edu.maplef.bookwild.utils;

import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

/**
 * 功能说明
 *
 * @author
 * @version 1.0
 */
/**
 * @author maple
 * 
 */
public class Utils {
	public Utils() {
	}

	/**
	 * 功能说明 将inStr中的内容用params中的内容替代
	 * 
	 * @param inStr
	 *            说明
	 * @param params
	 *            说明
	 * 
	 * @return 说明
	 */
	public static final String replaceStr(String inStr, Hashtable params) {
		String buf = "";
		String tokenName;
		String tokeValue;
		int i;

		if (params == null) {
			return inStr;
		}

		String outStr = inStr;
		inStr = inStr.toUpperCase();

		Enumeration ee = params.keys();

		while (ee.hasMoreElements()) {
			tokenName = ee.nextElement().toString();
			tokeValue = params.get(tokenName).toString().toUpperCase();
			tokenName = tokenName.toUpperCase();
			i = inStr.indexOf("[" + tokenName + "]");

			if (i == -1) {
				inStr = inStr + "  [" + tokenName + "]=" + tokeValue;
				outStr = outStr + "  [" + tokenName + "]=" + tokeValue;
			} else {
				do {
					inStr = inStr.substring(0, i + 1) + tokeValue
							+ inStr.substring(i + tokenName.length() + 1);
					outStr = outStr.substring(0, i + 1) + tokeValue
							+ outStr.substring(i + tokenName.length() + 1);
					i = inStr.indexOf("[" + tokenName);
				} while (i > 0);
			}
		}

		return outStr;
	}

	/**
	 * 功能说明
	 * 
	 * @param chr
	 *            说明
	 * @param length
	 *            说明
	 * 
	 * @return 说明
	 */
	public static StringBuffer getRepeatStrBuffer(char chr, int length) {
		StringBuffer sb = new StringBuffer(length);

		for (int i = 0; i < length; i++)
			sb.append(chr);

		return sb;
	}

	/**
	 * 功能说明 返回唯一值
	 * 
	 * @return 说明
	 */
	public static String getUniqueID() {
		return UUID.randomUUID().toString();
	}

	/**
	 * 功能说明 字符串转换如:make_date=>makeDate,
	 * 
	 * @param args
	 *            说明
	 */
	public static String initialUpper(String as_in) {
		char[] inc = as_in.trim().toCharArray();
		StringBuffer sb = new StringBuffer();
		boolean fir = false;

		for (int i = 0; i < inc.length; i++) {
			if (Character.isLetterOrDigit(inc[i])) {
				if (fir) {
					sb.append(Character.toUpperCase(inc[i]));
					fir = false;
				} else {
					sb.append(Character.toLowerCase(inc[i]));
				}
			} else {
				fir = true;
			}
		}

		;
		return sb.toString();
	}

	/**
	 * 功能说明 分页功能
	 * 
	 * @param page
	 *            说明 第几页
	 * @param pageCount
	 *            说明 每页记录数
	 * @param srcArrayList
	 *            说明 源数组
	 * 
	 * @return 说明
	 */
	public static ArrayList getArrayListByPage(int page, int pageCount,
			ArrayList srcArrayList) {
		ArrayList resultArrayList = new ArrayList();

		for (int i = (page - 1) * pageCount; i < (page * pageCount); i++) {
			if (srcArrayList.size() < (i + 1)) {
				break;
			}

			resultArrayList.add(srcArrayList.get(i));
		}

		return resultArrayList;
	}

	public static String[] split(String str, char separatorChar) {
		if (str == null) {
			return null;
		}
		int len = str.length();
		if (len == 0) {
			return new String[0];
		}
		List list = new ArrayList();
		int i = 0, start = 0;
		boolean match = false;
		while (i < len) {
			if (str.charAt(i) == separatorChar) {
				if (match) {
					list.add(str.substring(start, i));
					match = false;
				}
				start = ++i;
				continue;
			}
			match = true;
			i++;
		}
		if (match) {
			list.add(str.substring(start, i));
		}
		return (String[]) list.toArray(new String[list.size()]);
	}

	/**
	 * 获取任意两个日期间的天数
	 * 
	 * @param 起始日期
	 *            , 结束日期
	 * @return 天数
	 * @用法 SimpleDateFormat firstDate = new SimpleDateFormat("yyyy-MM-dd");
	 *     SimpleDateFormat lastDate = new SimpleDateFormat("yyyy-MM-dd");
	 *     String sDate = "2003-02-01"; String eDate = "2004-02-20"; Date
	 *     datFirstDate = firstDate.parse(sDate); Date datLastDate =
	 *     lastDate.parse(eDate); int sInt = getDayCount(datFirstDate,
	 *     datLastDate); System.out.println(datFirstDate + " 和 " + datLastDate +
	 *     " 之间相隔 " + sInt + " 天");
	 */
	public static int getDayCount(Date tStartDate, Date tEndDate) {
		int iRetVal = 0;
		GregorianCalendar calendar = (GregorianCalendar) GregorianCalendar
				.getInstance();

		calendar.setTime(tStartDate);

		GregorianCalendar calendar2 = (GregorianCalendar) GregorianCalendar
				.getInstance();

		calendar2.setTime(tEndDate);

		int iMaxDays = 0;
		String currentDate = null;

		while (calendar.before(calendar2)) {
			if (calendar.isLeapYear(calendar.get(GregorianCalendar.YEAR))) {
				iMaxDays = 366;
			} else {
				iMaxDays = 365;
			}

			++iRetVal;

			calendar.roll(GregorianCalendar.DAY_OF_YEAR, true);

			if (calendar.get(GregorianCalendar.DAY_OF_YEAR) == iMaxDays) {
				calendar.roll(GregorianCalendar.YEAR, 1);
				calendar
						.set(GregorianCalendar.MONTH, GregorianCalendar.JANUARY);
				calendar.set(GregorianCalendar.DAY_OF_MONTH, 1);
			}
		}

		return iRetVal;
	}

	public static String getJavascript(String[] arraySource) {
		String resultStr = "";
		if (arraySource == null) {
			return resultStr;
		}
		for (int i = 0; i < arraySource.length; i++) {
			resultStr += "\"" + arraySource[i] + "\",";
		}
		if (resultStr.length() > 0) {
			resultStr = resultStr.substring(0, resultStr.length() - 1);
		}
		return resultStr;
	}

	public static String nullToEmpty(String src) {
		if (src == null) {
			src = "";
			return src;
		}
		if (src.equalsIgnoreCase("NULL")) {
			src = "";
			return src;
		}
		return src;

	}

	public static String formatSqlValue(ArrayList al, String fieldName) {
		String res = "";
		for (int i = 0; i < al.size(); i++) {
			HashMap hm = (HashMap) al.get(i);
			String cur = StrCharUtil.formatNullStr(hm.get(fieldName));
			res += (cur + ",");
		}
		return res.substring(0, res.length() - 1);
	}

	/**
	 * 用 newString 替换 line 中的所有的 OldString
	 * 
	 * @param line
	 *            原字符串
	 * @param oldString
	 *            被替换的字符串
	 * @param newString
	 *            新的要替换oldString的字符串
	 * 
	 * @return 返回所有oldString都被newString替换的字符串
	 */
	public static final String replace(String line, String oldString,
			String newString) {
		// 如果line是null，直接返回
		if (line == null) {
			return null;
		}
		int i = 0;
		// 如果在line中确实存在oldString那么将进行以下的替换
		if ((i = line.indexOf(oldString, i)) >= 0) {
			char[] line2 = line.toCharArray();
			char[] newString2 = newString.toCharArray();
			int oLength = oldString.length();
			StringBuffer buf = new StringBuffer(line2.length);
			buf.append(line2, 0, i).append(newString2);
			i += oLength;
			int j = i;
			while ((i = line.indexOf(oldString, i)) > 0) {
				buf.append(line2, j, i - j).append(newString2);
				i += oLength;
				j = i;
			}
			buf.append(line2, j, line2.length - j);
			return buf.toString();
		}
		// 如果在line中没有oldString 返回line
		return line;
	}

	/**
	 * 做不区分大小写的模式匹配，并用newString 来替换 oldString
	 * 
	 * @param line
	 *            原字符串
	 * @param oldString
	 *            被替换的字符串
	 * @param newString
	 *            新的要替换oldString的字符串
	 * 
	 * @return 返回所有oldString都被newString替换的字符串
	 */
	public static final String replaceIgnoreCase(String line, String oldString,
			String newString) {
		// 如果line是null，直接返回
		if (line == null) {
			return null;
		}
		String lcLine = line.toLowerCase();
		String lcOldString = oldString.toLowerCase();
		int i = 0;
		if ((i = lcLine.indexOf(lcOldString, i)) >= 0) {
			char[] line2 = line.toCharArray();
			char[] newString2 = newString.toCharArray();
			int oLength = oldString.length();
			StringBuffer buf = new StringBuffer(line2.length);
			buf.append(line2, 0, i).append(newString2);
			i += oLength;
			int j = i;
			while ((i = lcLine.indexOf(lcOldString, i)) > 0) {
				buf.append(line2, j, i - j).append(newString2);
				i += oLength;
				j = i;
			}
			buf.append(line2, j, line2.length - j);
			return buf.toString();
		}
		return line;
	}

	/**
	 * 用 newString 替换 line 中的所有的 OldString count返回被替换的数目
	 * 
	 * @param line
	 *            原字符串
	 * @param oldString
	 *            被替换的字符串
	 * @param newString
	 *            新的要替换oldString的字符串
	 * 
	 * @return 返回所有oldString都被newString替换的字符串
	 */
	public static final String replace(String line, String oldString,
			String newString, int[] count) {
		if (line == null) {
			return null;
		}
		int i = 0;
		if ((i = line.indexOf(oldString, i)) >= 0) {
			int counter = 0;
			counter++;
			char[] line2 = line.toCharArray();
			char[] newString2 = newString.toCharArray();
			int oLength = oldString.length();
			StringBuffer buf = new StringBuffer(line2.length);
			buf.append(line2, 0, i).append(newString2);
			i += oLength;
			int j = i;
			while ((i = line.indexOf(oldString, i)) > 0) {
				counter++;
				buf.append(line2, j, i - j).append(newString2);
				i += oLength;
				j = i;
			}
			buf.append(line2, j, line2.length - j);
			count[0] = counter;
			return buf.toString();
		}
		return line;
	}

	/**
	 * @param name
	 *            ：模板名
	 * @param template
	 *            ：模板字串，其中需替换的用${}包围
	 * @param map
	 *            ：值替换表
	 * @return
	 */
	public static String processTemplate(String name, String template, Map map) {
		Iterator ite = map.entrySet().iterator();
		String model = template;
		while (ite.hasNext()) {
			Map.Entry entry = (Map.Entry) ite.next();
			String key = (String) entry.getKey();
			String value = (String) entry.getValue();
			model = replace(model, key, value);
		}
		return model;
	}

	/**
	 * @param request
	 *            ：网页请求
	 * @param field
	 *            ：表单名
	 * @return：转换为UTF-8的值
	 * @throws UnsupportedEncodingException
	 */
	public static String toUTF8(HttpServletRequest request, String field)
			throws UnsupportedEncodingException {
		if (request.getParameter(field) != null)
			return new String(
					request.getParameter(field).getBytes("ISO8859-1"), "UTF-8");
		else
			return "";
	}

	/**
	 * @param url
	 *            ：调用的URL
	 * @return：成功否
	 */
	public static boolean callWebUrl(String url) {
		URL urlCach;
		try {
			urlCach = new URL(url);
			HttpURLConnection urlconCach = (HttpURLConnection) urlCach
					.openConnection();
			urlconCach.setDoOutput(true);
			urlconCach.setRequestMethod("POST");
			urlconCach.setUseCaches(false);
			urlconCach.setDefaultUseCaches(false);
			String ss = urlconCach.getResponseMessage();
			urlconCach.disconnect();
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	/**
	 * @param objArray
	 *            :初始化数组
	 * @param initValue
	 *            ：初始化值
	 * @return
	 */
	public static String[] initArray(String[] objArray, String initValue) {
		if (objArray != null) {
			for (int i = 0; i < objArray.length; i++)
				objArray[i] = initValue;
			return objArray;
		} else
			return null;
	}

	public static boolean isIP(String ip) {
		int count = 0;
		boolean isIP = true;
		String temp = ip;
		String tem = "";
		if (temp.charAt(0) == '.' || temp.charAt(temp.length() - 1) == '.'
				|| temp.length() > 15)
			isIP = false;
		temp = temp + '.';
		for (int i = 0; i < temp.length(); i++) {

			if (temp.charAt(i) == '.') {
				count++;
				if (Integer.parseInt(tem) > 255)
					isIP = false;
				tem = "";
				continue;
			}
			if (temp.charAt(i) < '0' || temp.charAt(i) > '9')
				isIP = false;
			tem += String.valueOf(temp.charAt(i));
		}
		if (count != 4)
			isIP = false;

		return isIP;
	}

	public static final String getClientAddress(HttpServletRequest request) {
		String address = request.getHeader("X-Forwarded-For");
		if (address != null && isIP(address)) {
			return address;
		}
		return request.getRemoteAddr();
	}

	/**
	 * 功能说明
	 * 
	 * @param args
	 *            说明
	 */
	public static void main(String[] args) throws Exception {

		System.out.println(isIP("127.210.0.1"));
		System.out.println(isIP("233.255.2220.1"));
		System.out.println(isIP("212.0.0.1"));

	}

}
